package org.execute.tool.faceRecognition;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class FaceDetector {

    static {
        try {
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        } catch (UnsatisfiedLinkError e) {
            try {
                // 从JAR包内资源加载DLL
                try (InputStream dllStream = FaceDetector.class.getResourceAsStream("/lib/opencv_java460.dll")) {
                    if (dllStream == null) {
                        throw new RuntimeException("找不到OpenCV DLL文件");
                    }

                    File tempDll = File.createTempFile("opencv", ".dll");
                    Files.copy(dllStream, tempDll.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    System.load(tempDll.getAbsolutePath());
                    tempDll.deleteOnExit();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                System.exit(-1);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String inputPath = "input.jpg";
        String outputPath = "output.jpg";

        CascadeClassifier faceDetector = new CascadeClassifier();
        try (InputStream is = FaceDetector.class.getResourceAsStream("/haarcascade_frontalface_alt.xml")) {
            if (is == null) {
                throw new IllegalStateException("分类器文件未找到");
            }

            File tempFile = File.createTempFile("cascade", ".xml");
            Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            faceDetector.load(tempFile.getAbsolutePath());
            tempFile.deleteOnExit();
        }

        Mat image = Imgcodecs.imread(inputPath);
        if (image.empty()) {
            throw new IllegalArgumentException("输入图片读取失败: " + inputPath);
        }

        Mat grayImage = new Mat();
        Imgproc.cvtColor(image, grayImage, Imgproc.COLOR_BGR2GRAY);

        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(
                grayImage, faceDetections,
                1.1, 3, 0,
                new Size(30, 30), new Size());

        for (Rect rect : faceDetections.toArray()) {
            Imgproc.rectangle(
                    image,
                    new Point(rect.x, rect.y),
                    new Point(rect.x + rect.width, rect.y + rect.height),
                    new Scalar(0, 255, 0), 2);
        }

        Imgcodecs.imwrite(outputPath, image);
        System.out.println("检测完成，发现 " + faceDetections.toArray().length + " 张人脸");
    }
}